﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace a_fung
{
	public partial class PrototypeItemWindow : Form
	{
		enum Action
		{
			NEW_ITEM,
			UPDATE_ITEM
		}

		Action action = Action.NEW_ITEM;
		string id = "";
		private static List<string> openedID = new List<string>();
		Prototype p = null;

		delegate void safeCallback();

		public PrototypeItemWindow(Prototype p)
		{
			InitializeComponent();
			this.p = p;
		}

		public PrototypeItemWindow(Prototype p, string id, PrototypeItem item)
		{
			InitializeComponent();
			this.p = p;
			action = Action.UPDATE_ITEM;
			ActionButton.Text = "Update";
			this.Text = "Update - " + item.title;
			this.id = id;

			TitleBox.Text = item.title;
			LocationBox.Text = item.location;
			StartDatePicker.Value = item.startDate;
			DueDatePicker.Value = item.dueDate;

			this.FormClosing += new FormClosingEventHandler(Cleanup);
		}

		void Cleanup(object sender, FormClosingEventArgs e)
		{
			if (!String.IsNullOrEmpty(id))
			{
				openedID.Remove(id);
			}
		}

		public void MyShow()
		{
			if (String.IsNullOrEmpty(id))
			{
				base.Show();
				return;
			}

			if (!openedID.Contains(id))
			{
				openedID.Add(id);
				base.Show();
			}
		}

		private void CancelButton_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void ActionButton_Click(object sender, EventArgs e)
		{
			new System.Threading.Thread(ActionButton_Click).Start();

			this.Hide();
		}

		private void ActionButton_Click()
		{
			PrototypeItem item = new PrototypeItem();

			item.id = id;
			item.title = TitleBox.Text;
			item.location = LocationBox.Text;
			item.startDate = StartDatePicker.Value;
			item.dueDate = DueDatePicker.Value;

			if (action == Action.NEW_ITEM)
			{
				p.AddItem(item);
			}
			else if (action == Action.UPDATE_ITEM)
			{
				p.UpdateItem(item);
			}

			this.Invoke(new safeCallback(Close));
		}
	}
}
